package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.StrategyCatalog;
import cn.wolfcode.wolf2w.query.QueryObject;
import cn.wolfcode.wolf2w.repository.StrategyCatalogRepository;
import cn.wolfcode.wolf2w.service.IStrategyCatalogService;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.vo.CatalogVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service
public class StrategyCatalogServiceImpl implements IStrategyCatalogService {

    @Autowired
    private MongoTemplate template;

    @Autowired
    private StrategyCatalogRepository repository;
    @Autowired
    private IStrategyService strategyService;

    @Override
    public Page<StrategyCatalog> query(QueryObject qo) {


        // 1. 查询对象
        Query query = new Query();

        // 2. 封装参数
        // 总条数
        long count = template.count(query, StrategyCatalog.class);
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(), Sort.Direction.ASC, "_id");

        query.with(pageable);

        List<StrategyCatalog> list = template.find(query, StrategyCatalog.class);

        return new PageImpl<>(list,pageable,count);
    }

    @Override
    public void saveOrUpdate(StrategyCatalog strategyCatalog) {
        if (StringUtils.hasLength(strategyCatalog.getId())){
            repository.save(strategyCatalog);
        }else {
            strategyCatalog.setId(null);
            repository.save(strategyCatalog);
        }
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public List<CatalogVO> list() {
        List<CatalogVO> list = new ArrayList<>();

        // 聚合查询
        TypedAggregation<StrategyCatalog> agg = Aggregation.newAggregation(StrategyCatalog.class,
                Aggregation.group("destName").      // 分组
                        push("name").as("names").       // 查询表中name列,分组存入names中
                        push("id").as("ids")        // 查询表中id列,分组存入ids中
        );
        AggregationResults<Map> result = template.aggregate(agg, Map.class);
        List<Map> datas = result.getMappedResults(); //将结果转化成list<map>   map描述一行数据

        for (Map data : datas) {
            CatalogVO vo = new CatalogVO();

            vo.setDestName(data.get("_id").toString());  //id
            List<Object> names = (List<Object>) data.get("names");  //攻略分类的名称集合
            List<Object> ids = (List<Object>) data.get("ids");  //攻略分类的ids集合

            List<StrategyCatalog> catalogList = new ArrayList<>(); //攻略分类对象

            for (int i = 0; i < names.size(); i++) {
                StrategyCatalog sc = new StrategyCatalog();
                String name = names.get(i).toString();
                String id = ids.get(i).toString();
                sc.setId(id);
                sc.setName(name);
                catalogList.add(sc);
            }
            vo.setMapList(catalogList);
            list.add(vo);
        }
        return list;
    }

    @Override
    public StrategyCatalog get(String catalogId) {

        return repository.findById(catalogId).orElse(null);
    }

    @Override
    public List<StrategyCatalog> queryStrategyCatalogs(String destId) {
        if (!StringUtils.hasLength(destId)) {
            return null;
        }
        List<StrategyCatalog> catalogs = repository.findByDestId(destId);

        for (StrategyCatalog catalog : catalogs) {
            String catalogId = catalog.getId();
            // 根据分类id获取对应的攻略
            Pageable pageable = PageRequest.of(0, 5, Sort.Direction.ASC, "_id");
            List<Strategy> strategies = strategyService.findByCatalogId(catalogId,pageable);
            catalog.setStrategies(strategies);
        }
        return catalogs;
    }


}
